<?php
use Phalcon\Mvc\View;
use Phalcon\Mvc\View\Engine\Volt as VoltEngine;

class GeneratorController extends ControllerBase
{

    public function indexAction()
    {

    }

    public function createAction()
    {
        $id     = $this->request->getPost('id');
        $plugin = $this->request->getPost('plugin');
        if ($plugin == 'page') {

            $tbl     = BASE_PATH . '/_site/' . $this->siteid . '/page/config.json';
            $tbl     = json_decode(file_get_contents($tbl), true);
            $path    = $tbl[$id]['path'];
            $infoUrl = BASE_PATH . '/_site/' . $this->siteid . '/page/' . $path . '.volt';
            $dir     = substr($path, 0, strrpos($path, '/'));
            $dir     = BASE_PATH . '/_site/' . $this->siteid . '/public/' . $dir;
            if (!is_dir($dir)) {
                $ret = mkdir($dir, 0777, true);
                //第三个参数为true即可以创建多极目录
                if (!$ret) {
                    $json = ['code' => 4, 'msg' => '目录创建失败'];
                    $this->response->setJsonContent($json);
                    return $this->response;
                }
            }
        }
        $view           = new View();
        $volt           = new VoltEngine($view);
        $elements       = new Elements();
        $compiler       = $volt->getCompiler();
        $info           = file_get_contents($infoUrl);
        $compilerString = $compiler->compileString($info);
        ob_start();
        include "VariableStream://" . $compilerString;
        $content = ob_get_contents(); //得到当前缓冲区的内容
        ob_end_clean(); //删除当前输出缓
        $file = fopen(BASE_PATH . '/_site/' . $this->siteid . '/public/' . $path . '.html', 'w');
        fwrite($file, $content);
        fclose($file);
        $json = ['code' => 0, 'msg' => null];

        $this->response->setJsonContent($json);
        return $this->response;
    }
}
